package com.example.cloudmaps;




import java.util.ArrayList;
import java.util.Collections;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class Friends extends Activity implements OnItemLongClickListener{
	
	String username="";
	String friend="";
	private static final String PHP_SEND = "http://softeng.cs.uwosh.edu/students/meyers11/PHPAddRequest.php";
	private static final String PHP_FRIEND = "http://softeng.cs.uwosh.edu/students/meyers11/PHPGetFriends.php";
	private static final String PHP_DELETE = "http://softeng.cs.uwosh.edu/students/meyers11/PHPDeleteFriends.php";
	final Context context = this;
	
	ArrayList<String> friendslist = new ArrayList<String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_friends);
		
		final ImageButton sendButton = (ImageButton) findViewById(R.id.sendBtn);
		
		sendButton.setOnClickListener(new View.OnClickListener() {
	        public void onClick(View v) {
	        	sendRequest();
	    		
	        }
	    
		});
		
		ListView lv = (ListView) findViewById(R.id.friendList);
		lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View v,
                    int index, long arg3) {
            	
            	ListView lv = (ListView) findViewById(R.id.friendList);
            	
            	friend = (lv.getItemAtPosition(index).toString());
            	
            	System.out.println("FRIEND " + friend);
            	
            	AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
    			alertDialogBuilder.setTitle("Delete Friend");

    			alertDialogBuilder
    				.setMessage("Delete Friend: " + friend + "?")
    				.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
    					public void onClick(DialogInterface dialog,int id) {
    						new DeleteFriendTask().execute(friend,username);
    						dialog.cancel();
    					}
    				})
    				.setNegativeButton("No",new DialogInterface.OnClickListener(){
    					public void onClick(DialogInterface dialog,int id) {
    						dialog.cancel();
    					}
    				  });

    				AlertDialog alertDialog = alertDialogBuilder.create();

    				alertDialog.show();
                return false;
            	}
        }); 
		
		TextView searchBar = (TextView) findViewById(R.id.searchfriends);
		searchBar.addTextChangedListener(new TextWatcher(){

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				new SearchFriendsTask().execute(s);
			}
			
		});
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		new getLoginInfo().execute();
		new GetFriendsTask().execute();
	}
	
	@Override
	public void onBackPressed() {
		Intent myIntent = new Intent(Friends.this, MainActivity.class);
		startActivityForResult(myIntent, 0);
		finish();
	}

	
	private void sendRequest(){
		AlertDialog.Builder alert = new AlertDialog.Builder(this);   

	    LinearLayout lila1= new LinearLayout(this);
	    lila1.setOrientation(1); 
	    final EditText to = new EditText(this); 
	    to.setHint("Username");
	    TextView To = new TextView(this);
	    alert.setTitle("Send Friend Request");  
	    To.setText("To :");
	    To.setTextSize(20);
	    To.setPadding(15,0,0,0);
	    lila1.addView(To);
	    lila1.addView(to);
	    alert.setView(lila1);

		alert.setPositiveButton("Send", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
		  String sendTo = to.getText().toString();

		  if (sendTo.equals("") || sendTo.equals(null)){
				Context context = getApplicationContext();
				CharSequence text = "Enter a Username to send Friend Request To";
				int duration = Toast.LENGTH_SHORT;
			
				Toast toast = Toast.makeText(context, text, duration);
				toast.show();
		  }
		  else{
			  new SendRequestTask().execute(sendTo,username);
		  }
		  
		  }
		});

		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		  public void onClick(DialogInterface dialog, int whichButton) {
		    // Cancelled.
		  }
		});

		alert.show();
		
	}
	
	//Get Login Info
		private class getLoginInfo extends AsyncTask<Void, Void, String>{
			@Override
			protected String doInBackground(Void... nothing) {
				
				MapDataSource mds2 = new MapDataSource(Friends.this);
				
				mds2.open();
				
				try {
					username = mds2.getUsername();
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				mds2.close();
				
				return username;
			}
			
			@Override
			protected void onPostExecute(String whatever) {
				if (username.equals("user")){
					Intent myIntent = new Intent(Friends.this, LoginActivity.class);
					startActivityForResult(myIntent, 0);
					return;
				}
				else{
					return;
				}
			}
		}
		
		public class SendRequestTask extends AsyncTask<String, String, String> {
			@Override
			protected String doInBackground(String... params) {
				// TODO: attempt authentication against a network service.

				ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
				
				String response="false";
				if(networkInfo != null && networkInfo.isConnected())
				{
					ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
					n.add(new BasicNameValuePair("touser", params[0]));
					n.add(new BasicNameValuePair("fromuser", params[1]));
					
					
					HttpClient httpClient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost(PHP_SEND);
					
					
					
					try
					{
						httppost.setEntity(new UrlEncodedFormEntity(n));
						ResponseHandler<String> respondHandler = new BasicResponseHandler();
						response = httpClient.execute(httppost, respondHandler);
					}
					catch(Exception e){
						
					}
				}
				
				return response;
			}
			
			@Override
			protected void onPostExecute(String whatever) {
				if(!whatever.equals("false")){
					Context context = getApplicationContext();
					CharSequence text = "Request Sent!";
					int duration = Toast.LENGTH_SHORT;
				
					Toast toast = Toast.makeText(context, text, duration);
					toast.show();
					
				}
			}
		}
		
		private class SearchFriendsTask extends AsyncTask<CharSequence, Integer, ArrayList<String>>{

			@Override
			protected ArrayList<String> doInBackground(CharSequence... searchChars) {
				ArrayList<String> search = new ArrayList<String>();
				
				for(String c : Friends.this.friendslist){
					if(c.toLowerCase().contains(searchChars[0].toString().toLowerCase()) || searchChars.toString().equals("")){
						search.add(c);
					}
				}
				return search;
			}
			
	        @Override
	        protected void onPostExecute(ArrayList<String> friendList) {
	        	ListView lv;
	        	lv=(ListView)findViewById(R.id.friendList);
	            lv.setAdapter(new ArrayAdapter<String>(Friends.this, android.R.layout.simple_list_item_1, friendList));        
	        }
			
		}
		
		public class DeleteFriendTask extends AsyncTask<String, String, String> {
			@Override
			protected String doInBackground(String... params) {
				// TODO: attempt authentication against a network service.

				ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
				
				String response="false";
				if(networkInfo != null && networkInfo.isConnected())
				{
					ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
					n.add(new BasicNameValuePair("username1", params[0]));
					n.add(new BasicNameValuePair("username2", params[1]));
					
					
					HttpClient httpClient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost(PHP_DELETE);
					
					
					
					try
					{
						httppost.setEntity(new UrlEncodedFormEntity(n));
						ResponseHandler<String> respondHandler = new BasicResponseHandler();
						response = httpClient.execute(httppost, respondHandler);
					}
					catch(Exception e){
						
					}
				}
				
				return response;
			}
			
			@Override
			protected void onPostExecute(String whatever) {
				if(!whatever.equals("false")){
					Context context = getApplicationContext();
					CharSequence text = "Removed Friend!";
					int duration = Toast.LENGTH_SHORT;
				
					Toast toast = Toast.makeText(context, text, duration);
					toast.show();
					new GetFriendsTask().execute();
					
				}
			}
		}
		
		public class GetFriendsTask extends AsyncTask<Void, Void, ArrayList<String>> {
			@Override
			protected ArrayList<String> doInBackground(Void... params) {
				// TODO: attempt authentication against a network service.
				String response = "";
				ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
				
				ArrayList<String> friends = new ArrayList<String>(); 
				
				if(networkInfo != null && networkInfo.isConnected())
				{
					ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
					n.add(new BasicNameValuePair("username1", username));
					
					HttpClient httpClient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost(PHP_FRIEND);
					try
					{
						httppost.setEntity(new UrlEncodedFormEntity(n));
						ResponseHandler<String> respondHandler = new BasicResponseHandler();
						response = httpClient.execute(httppost, respondHandler);
						
						try{

							JSONArray jArray = new JSONArray(response);
							
							JSONObject json_data = null;

							for(int i = 0; i < jArray.length(); i++)
							{
								json_data = jArray.getJSONObject(i);
								
								String username2 = "";
								
								username2 = json_data.getString("username2");

								friends.add(username2);
							}
							
						}catch(JSONException e1){
							e1.printStackTrace();
						}
					}
					catch(Exception e){
						
					}
				}
				
				return friends;
			}
			
			@Override
			protected void onPostExecute(ArrayList<String> resp){
				
				Collections.sort(resp);
				friendslist = resp;
				//display friends
				ListView lv;
				lv=(ListView)findViewById(R.id.friendList);
				lv.setAdapter(new ArrayAdapter<String>(Friends.this,android.R.layout.simple_list_item_1 , resp));
			}
			
		}

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			// TODO Auto-generated method stub
			return false;
		}

}
